package com.argticling.dao.impl;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import com.argticling.dao.impl.hibernate.HibernateUtil;
import com.argticling.dao.impl.hibernate.InfrastructureException;
import com.argticling.model.Article;
import com.argticling.model.Profile;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import com.argticling.dao.interf.UserDAO;
import com.argticling.model.User;
import com.argticling.model.chanel.Contact;

public class UserDAOImplementation extends AbstractDAOImplementation implements UserDAO {

        public List<User> getUser() {
        return HibernateUtil.getSession().createCriteria(User.class).list();
    }

    public void createNewUser(String username, String password, String name, String surname, String role)
            throws InfrastructureException {
        HibernateUtil.beginTransaction();
        String encryptpass = md5convert(password);
        User user = new User(username, encryptpass, name, surname, role);
        HibernateUtil.persist(user);
        HibernateUtil.commitTransaction();
    }

    public void deleteUser(String userName) {
        HibernateUtil.beginTransaction();


        User user = (User) HibernateUtil.getSession().createQuery("from User as " +
                "user where user.username = ?").setString(0, userName).uniqueResult();

        if (user == null) {
            System.out.println("There's no user with that username");
            return;
        }

        HibernateUtil.getSession().delete(user);
        HibernateUtil.commitTransaction();
    }


    public boolean modifyPassword(String uname, String oldPassword, String newPassword) {
        HibernateUtil.beginTransaction();
        String encryptpassOld = md5convert(oldPassword);
        String encryptpassNew = md5convert(newPassword);
        User user = (User) HibernateUtil.getSession().createQuery("from User as " +
                "user where user.password = ? AND user.username = ? ").setString(0, encryptpassOld).setString(1, uname).uniqueResult();

        if (user == null) {
            return false;
        }

        user.setPassword(encryptpassNew);

        HibernateUtil.getSession().update(user);
        HibernateUtil.commitTransaction();
        return true;
    }

    public void modifyEmail(String oldMail, String newMail) {
        HibernateUtil.beginTransaction();

        User user = (User) HibernateUtil.getSession().createQuery("from User as " +
                "user where user.password = ?").setString(0, oldMail).uniqueResult();
    }


    public static List<User> getAll() {
        return new UserDAOImplementation().getUser();
    }

    public boolean checkIfUserExists(String uname, String pass) {

    	String password = md5convert(pass);
    	Session session = new HibernateUtil().getSession();
        User user = (User) session.createQuery("from User as " +
                "user where user.username =? AND user.password =?").setString(0, uname).setString(1, password).uniqueResult();
        
        if (user == null) {
            return false;
        } else {
            return true;
        }
    }
    
    public boolean checkIfUserExists(String uname) {
    	Session session = new HibernateUtil().getSession();
        User user = (User) session.createQuery("from User as " +
                "user where user.username =?").setString(0, uname).uniqueResult();
        
        if (user == null) {
            return false;
        } else {
            return true;
        }
    }

    public User getUserByName(String uname) {
    	HibernateUtil.beginTransaction();
    	
    	System.out.println("string: "+uname);
        
    	User user = (User) HibernateUtil.getSession().createQuery("FROM User as " +
                "user where user.username = ?").setString(0, uname).uniqueResult();
        
    	System.out.println("user: "+user.getUsername());
        
    	HibernateUtil.getSession().update(user);
        HibernateUtil.commitTransaction();
        
        return user;

    }

    public String md5convert(String password) {
        StringBuffer hexString = new StringBuffer();
        byte[] defaultBytes = password.getBytes();
        try {
            MessageDigest algorithm = MessageDigest.getInstance("MD5");
            algorithm.reset();
            algorithm.update(defaultBytes);
            byte messageDigest[] = algorithm.digest();


            for (int i = 0; i < messageDigest.length; i++) {
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            }
        } catch (
                NoSuchAlgorithmException nsae) {

        }
        return hexString.toString();
    }

    public void delete(String id) {
        User pojo = getUserById(id);
        Session session = new HibernateUtil().getSession();
        try {
            session.delete(pojo);
            session.beginTransaction().commit();
        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
    }

    public User getUserById(String id) {
        return (User) new HibernateUtil().getSession().createQuery("FROM User as user where " +
        "user.id = ?").setString(0, id).uniqueResult();
    }
    
    public List<Article> getAllArticlesofUser(String userName) {
		List<Article> articles = HibernateUtil
				.getSession()
				.createQuery(
						"from Article as "
								+ "article where article.authorId = ?")
				.setString(0, userName).list();
		return articles;
	}
}
